package com.xzx.flink.streamapi.transform;

import com.xzx.flink.bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2021-08-24 11:11 下午
 */
public class Transform_06_Split_Select {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> streamSource = env.readTextFile("/Users/xinzhixuan/work/git/flink-study-java/src/main/resources/sensor.txt");
        SingleOutputStreamOperator<SensorReading> map = streamSource.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String value) throws Exception {
                String[] split = value.split(" ");
                return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
            }
        });

        OutputTag<SensorReading> high = new OutputTag<>("high", TypeInformation.of(SensorReading.class));
        OutputTag<SensorReading> low = new OutputTag<>("low", TypeInformation.of(SensorReading.class));

        SingleOutputStreamOperator<SensorReading> process = map.process(new ProcessFunction<SensorReading, SensorReading>() {
            @Override
            public void processElement(SensorReading value, ProcessFunction<SensorReading, SensorReading>.Context ctx, Collector<SensorReading> out) throws Exception {
                if (value.getTemperature() < 32) {
                    ctx.output(low, value);// 输出到low流
                } else {
//                    out.collect(value);
                    ctx.output(high, value);
                }
            }
        });
//        process.print("high");
        process.getSideOutput(low).print("low");
        process.getSideOutput(high).print("high");


        env.execute(Transform_06_Split_Select.class.getName());
    }
}
